import { useEffect, useState } from 'react';
import { getMenuList } from '@/services/menu';

const resetData = (list: any[]): any[] => {
  return list?.map((item) => ({
    ...item,
    label: item.menuName,
    value: item.menuId,
    children: item.children ? resetData(item.children) : undefined,
  }));
};
export type MenuItem = {
  menuId: number;
  parentId: number;
  menuName: string;
  children?: MenuItem[];
  [key: string]: any;
};

function buildMenuTree(list: MenuItem[]): MenuItem[] {
  const map: Record<number, MenuItem> = {};
  const tree: MenuItem[] = [];

  // 1️⃣ 初始化 map
  list.forEach((item) => {
    map[item.menuId] = { ...item, children: [] };
  });

  // 2️⃣ 构建父子关系
  list.forEach((item) => {
    const parent = map[item.parentId];
    if (parent) {
      parent.children?.push(map[item.menuId]);
    } else {
      // parentId = 0 或 不存在，说明是根节点
      tree.push(map[item.menuId]);
    }
  });

  // 3️⃣ 清理空 children
  const cleanEmptyChildren = (nodes: MenuItem[]) => {
    nodes.forEach((node) => {
      if (node.children && node.children.length > 0) {
        cleanEmptyChildren(node.children);
      } else {
        node.children = undefined; // 空数组改为 undefined
      }
    });
  };

  cleanEmptyChildren(tree);

  return tree;
}
export { buildMenuTree };
export const useMenuModel = () => {
  //   const { data, ...rest } = await getMenuList(params);
  const [menuTree, setMenuTree] = useState<any[]>([]);
  useEffect(() => {
    fetchMenuTree();
  }, []);
  const fetchMenuTree = async () => {
    const { data } = await getMenuList();
    setMenuTree(resetData(buildMenuTree(data)));
  };
  return {
    menuTree,
    fetchMenuTree,
  };
};
